package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Community;
import com.qf.pojo.Tenement;
import com.qf.service.CommunityService;
import com.qf.service.TenementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("community")
public class CommunityController {

    @Autowired
    private CommunityService communityService;
    @Autowired
    private TenementService tenementService;

    @RequestMapping("findAll")
    public String findAll(
            @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize,
            Model model) {

        PageHelper.startPage(pageNum,pageSize);
        List<Community> communities = communityService.selectByExample();
        PageInfo<Community> communityPageInfo = new PageInfo<>(communities);
        model.addAttribute("communityPageInfo",communityPageInfo);
        List<Tenement> tenements = tenementService.findAll();
        model.addAttribute("tenements",tenements);

        return "listcommunity.html";
    }

    @RequestMapping("findById")
    public String findById(Integer id,Model model) {

        Community community = communityService.findById(id);
        model.addAttribute("community",community);
        List<Tenement> tenements = tenementService.findAll();
        model.addAttribute("tenements",tenements);

        return "";
    }

    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Community community, Integer id) {

        if (id != null) {
            communityService.updateCommunity(community);
        }else {
            communityService.insertCommunity(community);
        }
        return "redirect:/community/findAll";
    }

    @RequestMapping("deleteById")
    public String deleteById(Integer id) {

        communityService.deleteById(id);

        return "";
    }

}
